import { Suspense } from "react";
import { useRoutes, RouteObject, Navigate } from "react-router-dom";
import { Spin } from "antd";
import { useSelector } from "react-redux";

import RouteTable, { SyncRoute } from "./routes";
import { RootStateI } from "../types/system";

// 路由拦截
const RequireAuth = (props: {
  route: SyncRoute;
  children: React.ReactElement;
}) => {
  const user = useSelector((state: RootStateI) => state.user);
  // const navigate = useNavigate();
  if (props?.route?.meta?.title) {
    document.title = "XX系统-" + props.route.meta.title;
  }

  // You should call navigate() in a React.useEffect(), not when your component is first rendered.
  if (props?.route?.meta?.needLogin && !user.token) {
    // 看是否登录
    // navigate("/login");
  }
  return props.children;
};

//懒加载处理
const syncRouter = (routes: Array<SyncRoute>): RouteObject[] => {
  let mRouteTable: RouteObject[] = [];
  routes.forEach((route) => {
    mRouteTable.push({
      path: route.path,
      element: (
        <Suspense
          fallback={
            <div style={{ textAlign: "center" }}>
              <Spin size="large" data-testid="spin" />
            </div>
          }
        >
          <RequireAuth route={route}>
            <route.component />
          </RequireAuth>
        </Suspense>
      ),
      children: route.children && syncRouter(route.children),
    });
  });
  return mRouteTable;
};

const RootRoutes: () => React.ReactElement<
  any,
  string | React.JSXElementConstructor<any>
> | null = () => useRoutes(syncRouter(RouteTable)); //暴露为一个函数

export default RootRoutes;
